package com.zyong.encryption.client.netty.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zyong.encryption.client.config.NettyConfig;
import com.zyong.encryption.common.enums.SerializeProtocolEnum;
import com.zyong.encryption.common.netty.NettyPipelineInit;

import java.util.concurrent.TimeUnit;

/**
 * NettyClientHandlerInitializer.
 * @author xiaoyu
 */
@Component
public class NettyClientHandlerInitializer extends ChannelInitializer<SocketChannel> {

    private final NettyClientMessageHandler nettyClientMessageHandler;

    private NettyConfig nettyConfig;

    private SerializeProtocolEnum serializeProtocolEnum;

    private DefaultEventExecutorGroup servletExecutor;

    @Autowired
    public NettyClientHandlerInitializer(final NettyClientMessageHandler nettyClientMessageHandler) {
        this.nettyClientMessageHandler = nettyClientMessageHandler;
    }

    public void setServletExecutor(final DefaultEventExecutorGroup servletExecutor) {
        this.servletExecutor = servletExecutor;
    }

    public void setTxConfig(final NettyConfig nettyConfig) {
        this.nettyConfig = nettyConfig;
        nettyClientMessageHandler.setTxConfig(nettyConfig);
    }

    public void setSerializeProtocolEnum(final SerializeProtocolEnum serializeProtocolEnum) {
        this.serializeProtocolEnum = serializeProtocolEnum;
    }

    @Override
    protected void initChannel(final SocketChannel socketChannel) {
        final ChannelPipeline pipeline = socketChannel.pipeline();
        NettyPipelineInit.serializePipeline(serializeProtocolEnum, pipeline);
        pipeline.addLast("timeout", new IdleStateHandler(nettyConfig.getHeartTime(), nettyConfig.getHeartTime(), nettyConfig.getHeartTime(), TimeUnit.SECONDS));
        pipeline.addLast(nettyClientMessageHandler);
    }

}
